<script setup>
import { computed, ref, watch, defineProps, defineEmits } from "vue";
import axios from "axios";

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  focusTblName: {
    type: String,
    default: "vlt_tmp_a",
  },
  visible: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:modelValue", "update:visible", "refresh"]);

const setlId = ref("");
const loading = ref(false);
const localRows = ref([]);

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit("update:visible", val),
});

watch(
  () => props.modelValue,
  (rows) => {
    localRows.value = Array.isArray(rows) ? [...rows] : [];
  },
  { immediate: true }
);

const displayedColumns = computed(() => {
  if (!localRows.value.length) return [];
  const keys = Object.keys(localRows.value[0] ?? {});
  return keys.filter((key) =>
    localRows.value.some((row) => {
      const value = row?.[key];
      return !(value === null || value === undefined || value === "");
    })
  );
});

const doQuery = async () => {
  let sql = "";
  if (!setlId.value?.trim()) {
    sql = "SELECT * FROM " + props.focusTblName + " WHERE ROWNUM <= 50";
  } else {
    sql = `SELECT * FROM ${
      props.focusTblName
    } WHERE setl_id = '${setlId.value.trim()}' AND ROWNUM <= 50`;
  }
  // 发送到后端 /api/rule_apply/query_sql_exec，post，参数：{ sql: sql }
  loading.value = true;
  await axios
    .post("/api/rule_apply/query_sql_exec", {
      sql: sql,
    })
    .then((response) => {
      loading.value = false;
      console.log("SQL execution response:", response.data);
      if (response.data.mark == "OK") {
        localRows.value = response.data.data || [];
        emit("update:modelValue", localRows.value);
        emit("refresh", localRows.value);
      }
    }).catch((error) => {
      loading.value = false;
      console.error("Error executing SQL:", error);
      alert("执行 SQL 出错: " + error.message);
    });
};
// 父组件点击这个 dialog 的时候，自动执行查询
watch(
  () => dialogVisible.value,
  (val) => {
    if (val) {
      doQuery();
    }
  }
);
</script>

<template>
  <el-dialog title="Rule SQL 结果" v-model="dialogVisible" width="80%">
    <div class="query-bar">
      <el-input
        v-model="setlId"
        placeholder="请输入 setl_id"
        @keyup.enter="doQuery"
        class="query-input"
      />
      <el-button type="primary" :loading="loading" @click="doQuery">
        查询
      </el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="localRows"
      height="500"
      border
      style="width: 100%"
      empty-text="暂无数据"
    >
      <el-table-column type="index" width="60" label="#" />
      <el-table-column
        v-for="col in displayedColumns"
        :key="col"
        :prop="col"
        :label="col"
        :min-width="120"
        show-overflow-tooltip
      />
    </el-table>
  </el-dialog>
</template>

<style scoped>
.query-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.query-input {
  flex: 1;
}
</style>
